﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;
using System.Threading;

namespace Prism.Core.Timer
{
    public class StopwatchTimer
    {
        public StopwatchTimer()
        {
            this.Stopwatch = new Stopwatch();

            this.SpinWait = new SpinWait();

            this.Interval = TimeSpan.FromMilliseconds(1d);

            this.TimerAction = new Action(delegate()
            {
                this.Stopwatch.Start();

                while (IsRunning)
                {
                    this.SpinWait.SpinOnce();

                    var elapsed = this.Stopwatch.Elapsed.TotalSeconds;

                    Debug.Print(elapsed.ToString());

                    if (elapsed > this.Interval.TotalSeconds)
                    {
                        if (this.Elapsed != null) this.Elapsed(this, new TimeElapsedEventArgs() { ElapsedTime = TimeSpan.FromSeconds(elapsed) });
                        this.Stopwatch.Restart();
                    }
                }
            });
        }

        /// <summary>
        /// 获取或者设置间隔时间。默认为1ms。
        /// </summary>
        public TimeSpan Interval { get; set; }

        /// <summary>
        /// 当间隔时间到了之后引发。
        /// </summary>
        public event EventHandler<TimeElapsedEventArgs> Elapsed;

        private Stopwatch Stopwatch;

        private SpinWait SpinWait;

        private Action TimerAction;

        /// <summary>
        /// 获取是否正在运行。
        /// </summary>
        public bool IsRunning { get; private set; }

        /// <summary>
        /// 开始运作。
        /// </summary>
        public void Start()
        {
            this.IsRunning = false;
            this.IsRunning = true;
            this.TimerAction.BeginInvoke(null, null);
        }

        /// <summary>
        /// 结束运作。
        /// </summary>
        public void Stop()
        {
            this.IsRunning = false;
        }
    }
}
